from django.shortcuts import render
from rest_framework.views import APIView
from celery_tasks.sms_code.tasks import send_sms_code
from rest_framework.response import Response
from yunfei.serializers import *
import random
import redis
from yunfei.models import *
# 短信验证码
class SmsView(APIView):
	def get(self,request):
		mobile = request.query_params.get('phone')
		data = random.randint(1000,9999)
		if mobile:
			resp = send_sms_code.delay(mobile,data)
			print('异步>>>',resp)
			if resp:
				rdc = redis.Redis()
				rdc.setex('sms_%s' % mobile,600,data)
				print('>>>',data)
				return Response({'msg':data,'code':200})
			else:
				return Response({'msg':'发送失败','code':500})
		else:
			return Response({'msg':'参数错误','code':400})
# 登陆
class Login(APIView):
	def post(self,request):
		mobile = request.data.get('phone')
		sms_code = request.data.get('sms_code')
		print('验证码>>',sms_code)
		rdc = redis.Redis()
		real_sms_code = rdc.get('sms_%s' % mobile)
		if not real_sms_code:
			return Response({'msg':'验证码不存在或已过期','code':500})
		if real_sms_code.decode() != sms_code:
			return Response({'msg':'验证码错误','code':500})
		# 判断是否第一次登陆
		try:
			user = User_mobile.objects.create(mobile=mobile)
			return Response({'msg':'注册并登陆成功','code':201})
		except Exception as e:
			return Response({'msg':'服务器错误','code':500})

